package com.cq.hd.order.processor.order;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cq.hd.common.constant.OrderNoteConstant;
import com.cq.hd.order.mapper.TbOrderItemMapper;
import com.cq.hd.order.mapper.TbOrderMapper;
import com.cq.hd.order.po.TbOrderItemPo;
import com.cq.hd.order.po.TbOrderPo;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单补贴重新计算
 *
 * @author Much
 * @since 2024/09/22 14:49
 */
@Component
public class OrderSubsidyRecalculateProcessor {

    @Resource
    private TbOrderMapper orderMapper;
    @Resource
    private TbOrderItemMapper orderItemMapper;

    // 订单免单，重新计算补贴
    @Transactional
    public void recalculate4Free(Long orderId) {
        TbOrderPo tbOrderPo = orderMapper.selectById(orderId);
        tbOrderPo.setOrderIncomeAmt(BigDecimal.ZERO);
        tbOrderPo.setOrderNote(OrderNoteConstant.TEN);
        tbOrderPo.setUpdateTime(LocalDateTime.now());
        orderMapper.updateById(tbOrderPo);

        List<TbOrderItemPo> tbOrderItemPos = listOrderItemsByOrderId(orderId);
        for (TbOrderItemPo tbOrderItemPo : tbOrderItemPos) {
            BigDecimal merchantAmt = tbOrderItemPo.getMerchantAmt();
            if (BigDecimal.ZERO.compareTo(merchantAmt) == 0) {
                continue;
            }
            BigDecimal totalSubsidyAmt = tbOrderItemPo.getTotalSubsidyAmt();
            tbOrderItemPo.setTotalSubsidyAmt(totalSubsidyAmt.add(merchantAmt));
            BigDecimal merchantSubsidyAmt = tbOrderItemPo.getMerchantSubsidyAmt();
            tbOrderItemPo.setMerchantSubsidyAmt(merchantSubsidyAmt.add(merchantAmt));
            tbOrderItemPo.setUpdateTime(LocalDateTime.now());
            orderItemMapper.updateById(tbOrderItemPo);
        }
    }

    private List<TbOrderItemPo> listOrderItemsByOrderId(Long orderId) {
        LambdaQueryWrapper<TbOrderItemPo> qw = Wrappers.<TbOrderItemPo>lambdaQuery()
                .eq(TbOrderItemPo::getOrderId, orderId);
        return orderItemMapper.selectList(qw);
    }

}
